const nt_api = require('nt_api.js')


// 网络请求
// method 需大写
function httpRequest(api, method, params, callback) {
  if (!module.exports.globalData.apiurl) {
    wx.getExtConfig({
      success: function (res) {
        module.exports.globalData = res.extConfig;
        httpMain(api, method, { 'content-type': 'application/x-www-form-urlencoded' }, params, callback);
      }
    })
  } else {
    httpMain(api, method, { 'content-type': 'application/x-www-form-urlencoded' }, params, callback);
  }
}
function httpRequestBody(api, method, params, callback) {
  if (!module.exports.globalData.apiurl) {
    wx.getExtConfig({
      success: function (res) {
        module.exports.globalData = res.extConfig;
        httpMain(api, method, {}, params, callback);
      }
    })
  } else {
    httpMain(api, method, {}, params, callback);
  }
}
// 实现网络请求
// data 数据说明：

// 最终发送给服务器的数据是 String 类型，如果传入的 data 不是 String 类型，会被转换成 String 。转换规则如下：

// 对于 GET 方法的数据，会将数据转换成 query string（encodeURIComponent(k) = encodeURIComponent(v) & encodeURIComponent(k)=encodeURIComponent(v)...）
// 对于 POST 方法且 header['content-type'] 为 application/ json 的数据，会对数据进行 JSON 序列化
// 对于 POST 方法且 header['content-type'] 为 application/ x - www - form - urlencoded 的数据，会将数据转换成 query string （encodeURIComponent(k) = encodeURIComponent(v) & encodeURIComponent(k)=encodeURIComponent(v)...）
function httpMain(api, method, header, params, success, fail, complete) {
  method = method ? method : 'GET';
  method = method.toUpperCase();// 转大写
  var apiurl = module.exports.globalData.apiurl + api;
  if (method == 'GET') {
    apiurl = module.exports.globalData.apiurl + api + '?appId=' + module.exports.globalData.appid + '&appid=' + module.exports.globalData.appid;
    // apiurl = module.exports.globalData.apiurl + api;
  } else if (method == 'POST') {
    params.appId = module.exports.globalData.appid;
    params.appid = module.exports.globalData.appid;
  }
  // console.log("httpRequest======" + apiurl);
  // console.log("httpRequest params ======");
  // console.log(params);
  wx.showLoading({
    title: '加载中',
  })
  wx.request({
    url: apiurl,
    data: params,
    header: header,
    method: method,
    dataType: 'json',
    success: function (data) {
      // console.log("httpRequest data ======");
      // console.log(data);
      wx.hideLoading();
      switch (data.data.code) {
        case 100:
          success(data.data);
          break;
        case 101:
          break;
        case 200:
          success(data.data);
          break
        // case -1:
          // wx.showModal({
          //   content: data.data.msg,
          //   showCancel: false,
          //   success: function(e){}
          // });
          // success(data.data);
          // break
        default:
          success(data.data);
          break;
      }
    },
    fail: function (data) {
      wx.showModal({
        content: JSON.stringify(data),
        showCancel: false,
        success: function(){}
      });
      wx.hideLoading();
      wx.showToast({
        title: '请求接口超时',
      })
    },
    complete: function (res) {
      // if (res.code != 100) {
      //   wx.showToast({
      //     title: '请求失败！',
      //     icon: 'fail',
      //     duration: 2000
      //   });
      // }
    }
  })
}


function setStyle(code) {
  var store = {
    data: code,
    last_time: Date.parse(new Date()) / 1000
  };

  return true;
}


function getStyle(data) {
  // var data = JSON.parse(data);
  // var skin = !data.skin ? '#28e018' : data.skin;
  var skin = !data ? '#28e018' : data;
  module.exports.that.setData({
    color: skin,
    setting: data,
  });
  wx.setNavigationBarColor({ backgroundColor: skin, frontColor: '#ffffff' });
}


//设置网站风格
function style() {

  // var skin = wx.getStorageSync('nt_skin');
  // var data = skin ? JSON.parse(skin) : [];
  // var _time = data.last_time ? data.last_time : Date.parse(new Date()) / 1000;
  // var this_time = Date.parse(new Date()) / 1000;
  // if (!skin || this_time >= _time) {
  //   Post('/api/data/getSkinSetting', {}, function (data) {
  //     wx.setStorageSync('nt_skin', JSON.stringify(data));
  //     module.exports.getStyle(JSON.stringify(data));
  //   });
  // } else {
  //   module.exports.getStyle(skin);
  // }

  module.exports.getStyle();

}


// 选择图片
function chooseImage(success, fail) {
  wx.chooseImage({
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      success(res.tempFilePaths);
    },
    fail: function (res) {
      fail(res);
    }
  })
}
// 预览图片
function previewImage(url, files) {
  wx.previewImage({
    current: url, // 当前显示图片的http链接
    urls: files // 需要预览的图片http链接列表
  })
}
// 上传文件
function uploadFile(url, filePath, name, formData, success, fail) {
  wx.showLoading({
    title: '上传中...',
  })
  if (!module.exports.globalData.apiurl) {
    wx.getExtConfig({
      success: function (res) {
        module.exports.globalData = res.extConfig;
        wx.uploadFile({
          url: module.exports.globalData.apiurl + url,
          filePath: filePath,
          name: name || 'file',
          formData: formData,
          success: function (res) {
            success(JSON.parse(res.data));
          },
          fail: function (e) {
            fail(e);
          },
          complete: function (e) {
            wx.hideLoading();
          }
        })
      }
    })
  } else {
    wx.uploadFile({
      url: module.exports.globalData.apiurl + url,
      filePath: filePath,
      name: name || 'file',
      formData: formData,
      success: function (res) {
        success(JSON.parse(res.data));
      },
      fail: function (e) {
        fail(e);
      },
      complete: function (e) {
        wx.hideLoading();
      }
    })
  }

}



// nt_tools

// 打印日志
function log(data, name) {
  name = name ? name : '';
  console.log("nt_log start " + name + "====================");
  console.log(data);
  console.log("nt_log end " + name + "====================");
}

// 返回上一页
function back(i) {
  var pages = getCurrentPages();
  var num = pages.length
  // i = i ? i : 1;
  i = i || 1;
  // wx.navigateBack({
  //   delta: num - i,
  // });
  wx.navigateBack({
    delta: i,
  });
}

// 格式化时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 单个数字转字符串
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 去除 Json 中的空属性、空数组
function deleteEmptyProperty(obj) {
  for (var i in obj) {
    var value = obj[i];
    if (typeof value === 'object') {
      if (Array.isArray(value)) {
        if (value.length == 0) {
          delete obj[i];
          continue;
        }
      }
      deleteEmptyProperty(value);
      if (isEmpty(value)) {
        delete obj[i];
      }
    } else {
      if (value === '' || value === null || value === undefined) {
        delete obj[i];
      } else {
      }
    }
  }
  return obj;
}
function isEmpty(obj) {
  for (var name in obj) {
    return false;
  }
  return true;
}

// 获取保存本地的用户 openid
function getOpenId() {
  // return 'o5Mp_4snnePCRBOkA4ablLltVqjM'
  let openId = '';
  try {
    openId = wx.getStorageSync('openId')
  } catch (e) {
    // Do something when catch error
  };
  return openId;
}
// 获取保存本地的 moduleId
function getModuleId() {
  let moduleId = '';
  try {
    moduleId = wx.getStorageSync('moduleId')
  } catch (e) {
    // Do something when catch error
  };
  return moduleId;
}
// 获取保存本地的用户 手机号
function getMobile() {
  let mobile = '';
  try {
    mobile = wx.getStorageSync('mobile')
  } catch (e) {
    // Do something when catch error
  };
  return mobile;
}
function getBuyerId() {
  let buyerId = '';
  try {
    buyerId = wx.getStorageSync('buyerId')
  } catch (e) {
    // Do something when catch error
  };
  return buyerId;
}

function checkMobile(str) {
  var re = /^1\d{10}$/
  if (re.test(str)) {
    return true
  } else {
    wx.showModal({
      content: '请输入正确的手机号',
      showCancel: false
    });
    return false
  }
}


module.exports = {
  api: nt_api,

  httpRequest: httpRequest,
  httpRequestBody: httpRequestBody,
  httpMain: httpMain,
  chooseImage: chooseImage,
  previewImage: previewImage,
  uploadFile: uploadFile,

  style: style,
  getStyle: getStyle,
  setStyle: setStyle,

  that: null,
  globalData: [],
  setting: [],

  formatTime: formatTime,
  log: log,
  back: back,
  deleteEmptyProperty: deleteEmptyProperty,
  getOpenId: getOpenId,
  getModuleId: getModuleId,
  getMobile: getMobile,
  getBuyerId: getBuyerId,
  checkMobile: checkMobile
}
